package com.aiyan.edu.framework.interceptor;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * restTemplate远程调用拦截器
 * <p>
 * 把来自上游的http的请求头向下传递
 *
 * @author: zqzhou
 * @create: 2019/11/23 23:08
 **/
public class HttpClientInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (null == requestAttributes) {
            return clientHttpRequestExecution.execute(httpRequest, bytes);
        }

        HttpServletRequest request = requestAttributes.getRequest();

        String authorization = request.getHeader("Authorization");
        if (!authorization.startsWith("Bearer ")) {
            return clientHttpRequestExecution.execute(httpRequest, bytes);
        }

        String jwt = authorization.substring(7);
        if (StringUtils.isEmpty(jwt)) {
            return clientHttpRequestExecution.execute(httpRequest, bytes);
        }

        HttpHeaders headers = httpRequest.getHeaders();

        // 这里只把Authorization bearer头设置进去

        headers.add("Authorization", "Bearer " + jwt);

        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
